package com.haibei.activity;

import java.util.ArrayList;
import java.util.HashMap;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;

import com.common.net.NetResult;
import com.common.task.BaseTask;
import com.common.task.NetCallBack;
import com.common.uitl.AssertTool;
import com.common.uitl.LogUtil;
import com.common.uitl.StringUtils;
import com.common.uitl.Tool;
import com.haibei.App;
import com.haibei.R;
import com.haibei.adapter.bean.ArticleCategory;
import com.haibei.adapter.bean.City;
import com.haibei.adapter.bean.PushMessage;
import com.haibei.net.NetInterface;
import com.haibei.receiver.MyReceiver;
import com.haibei.utils.ExampleUtil;
import com.haibei.utils.NotifyTool;

public class WelcomActivity extends BaseHaibeiActivity {

	private BaseTask mBaseTask;

	public static final String MESSAGE_RECEIVED_ACTION = "com.example.jpushdemo.MESSAGE_RECEIVED_ACTION";
	public static final String KEY_TITLE = "title";
	public static final String KEY_MESSAGE = "message";
	public static final String KEY_EXTRAS = "extras";
	public static boolean isStarted = false;

	private PushMessage mPushMessage;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		isStarted = true;
		NotifyTool.cancellNotify(WelcomActivity.this, MyReceiver.notifycationId);
		Intent i = getIntent();
		if (null != i) {
			int exit = i.getIntExtra("flag", 0);
			if (exit == -1) {// 收到推出的指令
				finish();
			} else {
				try {// 获取推送的数据
					mPushMessage = (PushMessage) i.getSerializableExtra(MyReceiver.push_bean);
				} catch (Exception e) {
					e.printStackTrace();
				}
				initView();
			}
		} else {
			initView();
		}

	}

	@Override
	protected void onDestroy() {
		super.onDestroy();
		isStarted = false;
	}

	@Override
	public void initView() {
		setContentView(R.layout.activity_welcome);
		ParseCityTask pt = new ParseCityTask();
		pt.execute();
	}

	private void requestListCategory() {
		HashMap<String, String> hmap = new HashMap<String, String>();
		getListCategory().execute(hmap);
	}

	private void gotoMainActivity() {
		if (null != mPushMessage) {
			Intent i = new Intent();
			i.setClass(WelcomActivity.this, MainActivity.class);
			i.putExtra(MyReceiver.push_bean, mPushMessage);
			LogUtil.i(App.tag, "welcome msg:" + mPushMessage.getId() + " msg:" + mPushMessage.getContent());
			startActivity(i);
		} else {
			Tool.startActivity(WelcomActivity.this, MainActivity.class);
		}
	}

	private void tideMenu(NetResult result) {
		try {
			ArrayList<ArticleCategory> categoryList = (ArrayList<ArticleCategory>) result.getData()[0];
			App.getApp().setCategoryItem(categoryList);
		} catch (Exception e) {
			e.printStackTrace();
			LogUtil.e(App.tag, " exception:加载类别出错！");
		}
	}

	private BaseTask getListCategory() {
		if (null != mBaseTask && !mBaseTask.isCancelled()) {
			mBaseTask.cancel(true);
		}
		mBaseTask = new BaseTask(new NetCallBack() {
			@Override
			public void onFinish(NetResult result) {
				if (null != result && result.isSuccess()) {
					tideMenu(result);
				}
				gotoMainActivity();// 无论成功失败，都要进入主页
			}

			@Override
			public NetResult onDoInBack(HashMap<String, String> paramMap) {
				NetResult netResult = null;
				try {
					netResult = NetInterface.getAriticleCategory(WelcomActivity.this, paramMap);
				} catch (Exception e) {
					e.printStackTrace();
				}
				return netResult;
			}
		});
		return mBaseTask;
	}

	class ParseCityTask extends AsyncTask<Void, Void, ArrayList<City>> {

		@Override
		protected void onPreExecute() {
			super.onPreExecute();
			App.mArrayListFirstLevelCity.clear();
		}

		@Override
		protected ArrayList<City> doInBackground(Void... params) {
			String citys = AssertTool.getStrFromAssert(WelcomActivity.this, "data/city.json");
			if (!StringUtils.isEmpty(citys)) {
				try {
					JSONArray jsa = new JSONArray(citys);
					for (int i = 0, isize = jsa.length(); i < isize; i++) {
						JSONObject jso = jsa.getJSONObject(i);// 一级城市
						String id = jso.getString("id");
						String name = jso.getString("name");
						City city = new City();
						city.setId(id);
						city.setName(name);
						App.cityIdMap.put(id, city);
						App.cityMap.put(name, city);
						if (jso.has("sub")) {// 添加子城市
							JSONArray subs = jso.getJSONArray("sub");
							for (int x = 0, xsize = subs.length(); x < xsize; x++) {
								JSONObject jsoSub = subs.getJSONObject(x);
								String subId = jsoSub.getString("id");
								String subName = jsoSub.getString("name");
								City subCity = new City();
								subCity.setId(subId);
								subCity.setName(subName);
								App.cityMap.put(subName, subCity);// 留待后用
								App.cityIdMap.put(subId, subCity);
								city.addSubCity(subCity);
							}
						}
						App.mArrayListFirstLevelCity.add(city);
					}
				} catch (JSONException e) {
					e.printStackTrace();
				}
			}
			return null;
		}

		@Override
		protected void onPostExecute(ArrayList<City> result) {
			super.onPostExecute(result);
			LogUtil.i(App.tag, "城市解析完毕");
			requestListCategory();
		}
	}

	public class MessageReceiver extends BroadcastReceiver {

		@Override
		public void onReceive(Context context, Intent intent) {
			if (MESSAGE_RECEIVED_ACTION.equals(intent.getAction())) {
				String messge = intent.getStringExtra(KEY_MESSAGE);
				String extras = intent.getStringExtra(KEY_EXTRAS);
				StringBuilder showMsg = new StringBuilder();
				showMsg.append(KEY_MESSAGE + " : " + messge + "\n");
				if (!ExampleUtil.isEmpty(extras)) {
					showMsg.append(KEY_EXTRAS + " : " + extras + "\n");
				}
				// 展示接受到的信息
			}
		}
	}
}
